package aula1e2;
import java.awt.List;
import java.io.*;
import java.net.*;
import java.util.LinkedList;



class UDPServer
{
	//static matriculas SistemaMatricula = new matriculas();
   public static void main(String args[]) throws Exception
      {
         DatagramSocket serverSocket = new DatagramSocket(9876);
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];
           
            LinkedList<String> listaMatriculas = new LinkedList<String>();
            
            while(true)
               {
                  DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                  serverSocket.receive(receivePacket);
                  String sentence = new String( receivePacket.getData(),0,receivePacket.getLength());
                  System.out.println("RECEIVED: " + sentence);
                  InetAddress IPAddress = receivePacket.getAddress();
                  int port = receivePacket.getPort();
                 String capitalizedSentence = sentence.toUpperCase(); 
                  String tokens[] = capitalizedSentence.split(" ");
                  
                  if(tokens[0].equals("REGISTER"))
                   {
                	  if(tokens[1].length() < 1 || tokens[2].length() < 1)
                		  System.out.print("Argumentos em falta");
                	  
                	  
                	  else
                	  {
                	  sendData = capitalizedSentence.getBytes();
                      DatagramPacket sendPacket =
                      new DatagramPacket(sendData, sendData.length, IPAddress, port);
                      serverSocket.send(sendPacket);
                      listaMatriculas.add(tokens[1]);
                      listaMatriculas.add(tokens[2]);
                      System.out.println("Novo Registo adicionado");
                      }
                  }
                  
                  else if(tokens[0].equals("LOOKUP"))
                  {
                	  if(listaMatriculas.contains(tokens[1]) == false)
                			  {
                		  
                		  		System.out.println("Cliente nao existe");
                			  }
                	  
                	  else
                	  {
                		  int i = listaMatriculas.indexOf(tokens[1]);
                		  String a = listaMatriculas.get(i+1);
                		  System.out.println("Registo encontrado : " + a);
                	  }
                  }
                  
                  else
                  {
                	  System.out.println("Comando nao reconhecido");
                  }
                  
               }
      }
}